package com.tyc.waitnotify;

import java.util.concurrent.TimeUnit;

/**
 * 使用wait notify 三个线程循环单元A B C 各10次
 * 使用wait notify注意事项：
 *      1.一定要在先获取对象的锁
 *      2.调用notify 等待线程并不会立刻返回 等到调用notify释放后
 */
public class WaitNotify {
    private volatile static String str = "A";
    private static byte[] lock = new byte[0];

    public static void main(String[] args) throws InterruptedException {
        Thread a = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    print("A","B");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread b = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    print("B","C");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        Thread c = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                try {
                    print("C","A");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });

        a.start();
        b.start();
        c.start();
        TimeUnit.SECONDS.sleep(1);
    }

    public static void print(String target,String newStr) throws InterruptedException {
        synchronized (lock){
            while (!str.equals(target)){
                lock.wait();
            }
            System.out.println(target);
            str = newStr;
            lock.notifyAll();
        }
    }
}
